package com.yingsheng.bi.hks.repository.dao.service;

import com.yingsheng.bi.hks.basic.consts.MsgDict;
import com.yingsheng.bi.hks.basic.enums.EnumConst;
import com.yingsheng.bi.hks.basic.exception.ServiceRuntimeException;
import com.yingsheng.bi.hks.repository.dao.mapper.RoleMapper;
import com.yingsheng.bi.hks.repository.dao.mapper.UserRoleMapper;
import com.yingsheng.bi.hks.repository.dao.po.Role;
import com.yingsheng.bi.hks.repository.dao.po.UserRole;
import com.yingsheng.bi.hks.repository.dao.po.UserRoleExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * Users表的数据库操作服务
 * 要求说明：
 * 1.一般情况下,要求参数不超过5个时方法入参逐个声明
 * 2.一般情况下,要求条件不超过3个时要在方法名上体现
 * 3.最好对方法入参做一定校验,尤其是对条件参数至少要做非空校验
 *
 * @author root
 */
@Repository
public class UserRoleDaoService implements DaoService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    public Role queryRoleByUserId(@NotNull String userId) {
        UserRoleExample example = new UserRoleExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<UserRole> userRoleList = userRoleMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(userRoleList)) {
            throw new ServiceRuntimeException(MsgDict.TABLE_DATA_ERROR);
        }
        UserRole userRole = userRoleList.get(0);
        return queryRoleByRoleId(userRole.getRoleId());
    }

    public Role createUserRole(@NotNull String userId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(EnumConst.Role.P01);
        userRole.setCreateTime(new Date());
        userRoleMapper.insertSelective(userRole);
        return queryRoleByRoleId(userRole.getRoleId());
    }

    public Role queryRoleByRoleId(@NotNull String roleId) {
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role == null) {
            throw new ServiceRuntimeException(MsgDict.TABLE_DATA_ERROR);
        }
        return role;
    }


}
